//
//  ANMessageCenterController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/6/23.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANMessageCenterController.h"
#import "MessageCenterCell.h"
#import "MessageCenterEntity.h"
#import "ANIMController.h"

@interface ANMessageCenterController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<MessageCenterEntity *> *dataSource;
@property (nonatomic) int pageNo;

@end

@implementation ANMessageCenterController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"消息中心";
    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    
    
    // 极光自定义消息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestData];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification
{
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    if ([message.allKeys containsObject:@"pushType"] && [message[@"pushType"] intValue] == 1 && [message[@"messageSource"] intValue] == 1) {
        NSLog(@"收到新的未读消息消息：%@",content);
        // 刷新
        self.pageNo = 1;
        [self requestData];
    }
}

- (void)requestData
{
    NSDictionary *body = @{
                           @"memberId":UserUtils.shared.vipId,
                           @"pageNo":@(self.pageNo),
                           @"pageSize":@20,
                           @"messageSource":@"1"
                           };
    [URLManager.shareManager getUrlStr:Api_MessageCenter_List parameters:body entityClass:[MessageCenterListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if ([baseEntity.code intValue] == 200) {
                MessageCenterListEntity *data = baseEntity.data;
                if (self.pageNo == 1) {
                    [self.dataSource removeAllObjects];
                    [self.tableView.mj_footer resetNoMoreData];
                    [self.tableView.mj_header endRefreshing];
                    if (data.data.count < 20) {
                        self.tableView.mj_footer.alpha = 0;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                else {
                    if (data.data.count < 20) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                }
                [self.dataSource addObjectsFromArray:data.data];
                [self.tableView reloadData];
            }
            else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

/// 删除
- (void)deleteRequest:(NSIndexPath *)indexPath
{
    MessageCenterEntity *entity = self.dataSource[indexPath.row];
    if (entity.chatRecordId == nil || entity.chatRecordId.length == 0) {
        return;
    }
    NSDictionary *body = @{
                           @"id":entity.chatRecordId
                           };
    [MBProgressHUD showActivityMessage:nil];
    [URLManager.shareManager postUrlStr:Api_MessageCenter_Del parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [MBProgressHUD showMessage:responseObj[@"message"]];
                [self.dataSource removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }
            else {
                [MBProgressHUD showMessage:responseObj[@"message"]];
            }
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)setupSubViews
{
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MessageCenterCell class] forCellReuseIdentifier:@"2019-6-23 10:14"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"2019-6-23 10:14" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.entity = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ANIMController *vc = [[ANIMController alloc] init];
    vc.orgId = self.dataSource[indexPath.row].orgId;
    vc.title = self.dataSource[indexPath.row].orgName;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self deleteRequest:indexPath];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, kTabBarHeight, 0);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.pageNo = 1;
            [weakSelf requestData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.pageNo++;
            [weakSelf requestData];
        }];;
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
